<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Supplier_Product_Price_Line extends ORM
{
    /**
     * @param $params
     * @return array
     * 插入报价信息
     */
    public static function set_calendar_quote($params)
    {
        $params = json_decode($params,true);
        $start_time = strtotime($params['start_time']);
        $end_time = strtotime($params['end_time']);

        $total_number = DB::select(DB::expr('min(number) AS number'))->from('line_suit_number')
            ->where("suit_id={$params['suit_id']} and number!='-1' and day>={$start_time} and day<={$end_time}")
            ->execute()->get('number');
        if($params['number']>$total_number && $total_number>0){
            $date = DB::select()->from('line_suit_number')
                ->where("suit_id={$params['suit_id']} and number={$total_number} and day>={$start_time} and day<={$end_time}")
                ->execute()->get('day');
            return array(
                'status' => false,
                'msg'    => date('Y-m-d',$date).'当前时间，库存不支持所设限购数',
            );
        }

        $day_num = ($end_time-$start_time)/86400;
        $product_id = DB::select()->from('line_suit')->where("id={$params['suit_id']}")->execute()->get('lineid');

        $adultbasicprice    = $params['adultbasicprice']?$params['adultbasicprice']:0;
        $childbasicprice    = $params['childbasicprice']?$params['childbasicprice']:0;
        $oldbasicprice      = $params['oldbasicprice']?$params['oldbasicprice']:0;
        $people4_basicprice = $params['people4_basicprice']?$params['people4_basicprice']:0;
        $people5_basicprice = $params['people5_basicprice']?$params['people5_basicprice']:0;
        $people6_basicprice = $params['people6_basicprice']?$params['people6_basicprice']:0;
        $room_balance       = $params['room_balance']?$params['room_balance']:0;
        $number             = $params['number']?$params['number']:0;
        $propgroup          = implode(',',$params['propgroup']);

        $insert_arr = array();
        $update_arr = array(
            'adultbasicprice'    => "adultbasicprice = CASE ",
            'adultprice'         => "adultprice = CASE ",
            'childbasicprice'    => "childbasicprice = CASE ",
            'childprice'         => "childprice = CASE ",
            'oldbasicprice'      => "oldbasicprice = CASE ",
            'oldprice'           => "oldprice = CASE ",
            'people4_basicprice' => "people4_basicprice = CASE ",
            'people4_price'      => "people4_price = CASE ",
            'people5_basicprice' => "people5_basicprice = CASE ",
            'people5_price'      => "people5_price = CASE ",
            'people6_basicprice' => "people6_basicprice = CASE ",
            'people6_price'      => "people6_price = CASE ",
            'number'             => "number = CASE ",
            'propgroup'          => "propgroup = CASE ",
        );

        $update_id = array();
        $update_day = array();
        for($i=0;$i<=$day_num;$i++){
            $start_time = $i>0?$start_time+86400:$start_time;
            $is_exist = DB::select()->from('line_suit_price')
                ->where("suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']}")
                ->execute()->current();
            $state = false;
            switch ($params['price_rule'])
            {
                case 1://全时段
                    $state = true;
                    break;
                case 2://按周
                    $week = date('w',$start_time)>0?date('w',$start_time):7;
                    if(in_array($week,$params['week_val'])){
                        $state = true;
                    }
                    break;
                case 3://按天
                    $month = date('j',$start_time);
                    if(in_array($month,$params['month_val'])){
                        $state = true;
                    }
                    break;
            }
            if(!$state){
                continue;
            }
            if($is_exist){
                $adultprice = bcadd($adultbasicprice,$is_exist['adultprofit'],2);
                $childprice = bcadd($childbasicprice,$is_exist['childprofit'],2);
                $oldprice = bcadd($oldbasicprice,$is_exist['oldprofit'],2);
                $people4_price = bcadd($people4_basicprice,$is_exist['people4_profit'],2);
                $people5_price = bcadd($people5_basicprice,$is_exist['people5_profit'],2);
                $people6_price = bcadd($people6_basicprice,$is_exist['people6_profit'],2);
                array_push($update_id,$is_exist['suitid']);
                array_push($update_day,$is_exist['day']);

                $sql = "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']}";
                $update_arr['adultbasicprice']    .= $sql." THEN '{$adultbasicprice}' ";
                $update_arr['adultprice']         .= $sql." THEN '{$adultprice}' ";
                $update_arr['childbasicprice']    .= $sql." THEN '{$childbasicprice}' ";
                $update_arr['childprice']         .= $sql." THEN '{$childprice}' ";
                $update_arr['oldbasicprice']      .= $sql." THEN '{$oldbasicprice}' ";
                $update_arr['oldprice']           .= $sql." THEN '{$oldprice}' ";
                $update_arr['people4_basicprice'] .= $sql." THEN '{$people4_basicprice}' ";
                $update_arr['people4_price']      .= $sql." THEN '{$people4_price}' ";
                $update_arr['people5_basicprice'] .= $sql." THEN '{$people5_basicprice}' ";
                $update_arr['people5_price']      .= $sql." THEN '{$people5_price}' ";
                $update_arr['people6_basicprice'] .= $sql." THEN '{$people6_basicprice}' ";
                $update_arr['people6_price']      .= $sql." THEN '{$people6_price}' ";
                $update_arr['number']             .= $sql." THEN '{$number}' ";
                $update_arr['propgroup']          .= $sql." THEN '{$propgroup}' ";
            }else{
                $value_arr = array(
                    $product_id,
                    $params['suit_id'],
                    $start_time,
                    $adultbasicprice,
                    $adultbasicprice,
                    $childbasicprice,
                    $childbasicprice,
                    $oldbasicprice,
                    $oldbasicprice,
                    $people4_basicprice,
                    $people4_basicprice,
                    $people5_basicprice,
                    $people5_basicprice,
                    $people6_basicprice,
                    $people6_basicprice,
                    $room_balance,
                    $number,
                    $params['channel_id'],
                    "'".$propgroup."'"
                );
                $insert_sql = "(".implode(',',$value_arr).")";
                array_push($insert_arr,$insert_sql);
            }
        }

        if(count($insert_arr)>0){
            $field_arr = array(
                'lineid',
                'suitid',
                'day',
                'adultbasicprice',
                'adultprice',
                'childbasicprice',
                'childprice',
                'oldbasicprice',
                'oldprice',
                'people4_basicprice',
                'people4_price',
                'people5_basicprice',
                'people5_price',
                'people6_basicprice',
                'people6_price',
                'roombalance',
                'number',
                'supplier_channel_id',
                'propgroup',
            );
            $insert_sql = "INSERT INTO sline_line_suit_price(`".implode('`,`',$field_arr)."`) VALUES ";
            $insert_sql.= implode(',',$insert_arr);
            $result = DB::query(1, $insert_sql)->execute();
        }
        if(count($update_id)>0){
            $update_sql = "UPDATE sline_line_suit_price SET ";
            $update_id = implode(',',$update_id);
            $update_day = implode(',',$update_day);
            foreach ($update_arr as $k=>$v){
                $update_sql.= $v."ELSE {$k} END,";
            }
            $update_sql = substr($update_sql,0,strlen($update_sql)-1);
            $update_sql.= " WHERE suitid IN({$update_id}) and day IN({$update_day}) ";
            $result = DB::query(1, $update_sql)->execute();
        }

        return array(
            'status' => $result || $result===0?true:false,
            'msg'    => $result || $result===0?'设置成功':'设置失败',
        );
    }

    /**
     * @param $params
     * @return array
     * 单天调价
     */
    public static function set_single_price($params)
    {

        $params = json_decode($params,true);
        $day = strtotime($params['set_date']);

        $lineid = DB::select('lineid')->from('line_suit')->where('id','=',$params['suit_id'])->execute()->get('lineid');

        $total_number = DB::select()->from('line_suit_number')->where("suit_id={$params['suit_id']} and day={$day}")->execute()->get('number');
        if(empty($total_number)){
            return array(
                'status' => false,
                'msg'    => '当前日期没有总库存！',
            );
        }
        if($params['number']>$total_number && $total_number!='-1'){
            return array(
                'status' => false,
                'msg'    => '限购数不得大于总库存',
            );
        }
        $propgroup = implode(',',$params['propgroup']);
        $price = DB::select()->from('line_suit_price')
            ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
            ->execute()->current();
        if($price){
            $adultprice = bcadd($price['adultprofit'],$params['adultbasicprice'],2);
            $childprice = bcadd($price['childprofit'],$params['childbasicprice'],2);
            $oldprice   = bcadd($price['oldprofit'],$params['childbasicprice'],2);
            $people4_price = bcadd($price['people4_profit'],$params['people4_basicprice'],2);
            $people5_price = bcadd($price['people5_profit'],$params['people5_basicprice'],2);
            $people6_price = bcadd($price['people6_profit'],$params['people6_basicprice'],2);
        }else{
            $adultprice = $params['adultbasicprice'];
            $childprice = $params['childbasicprice'];
            $oldprice = $params['oldbasicprice'];
            $people4_price = $params['people4_basicprice'];
            $people5_price = $params['people5_basicprice'];
            $people6_price = $params['people6_basicprice'];
        }

        $data = array(
            'childbasicprice'    => $params['childbasicprice'],
            'childprice'         => $childprice,
            'adultbasicprice'    => $params['adultbasicprice'],
            'adultprice'         => $adultprice,
            'oldbasicprice'      => $params['oldbasicprice'],
            'oldprice'           => $oldprice,
            'people4_basicprice' => $params['people4_basicprice'],
            'people4_price'      => $people4_price,
            'people5_basicprice' => $params['people5_basicprice'],
            'people5_price'      => $people5_price,
            'people6_basicprice' => $params['people6_basicprice'],
            'people6_price'      => $people6_price,
            'roombalance'        => $params['roombalance'],
            'number'             => $params['number'],
            'propgroup'          => $propgroup,
        );

        $exists = DB::select()->from('line_suit_price')
            ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
            ->execute()
            ->as_array();
        if(empty($exists)){
            $data['day']=$day;
            $data['suitid']=$params['suit_id'];
            $data['lineid']=$lineid;
            $result = DB::insert('line_suit_price', array_keys($data))->values(array_values($data))->execute();
        }else{
            $result = DB::update('line_suit_price')->set($data)
                ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
                ->execute();
        }

        return array(
            'status'             => $result || $result===0?true:false,
            'msg'                => $result || $result===0?'设置成功':'设置失败',
            'price'              => $params['adultbasicprice'],
            'childbasicprice'    => $params['childbasicprice'],
            'oldbasicprice'      => $params['oldbasicprice'],
            'people4_basicprice' => $params['people4_basicprice'],
            'people5_basicprice' => $params['people5_basicprice'],
            'people6_basicprice' => $params['people6_basicprice'],
            'roombalance'        => $params['roombalance'],
            'number'             => $params['number'],
            'date'               => $params['set_date'],
        );
    }

    /**
     * @param $params
     * @return array
     * 根据渠道id获取报价信息
     */
    public static function get_suit_price($params)
    {
        $params = json_decode($params,true);
        $year = empty($params['year'])?date('Y'):$params['year'];
        $month = empty($params['month'])?date('m'):$params['month'];

        $start_time = strtotime($year.'-'.$month.'-01');
        $last_day = date('t',$start_time);
        $end_time = strtotime($year.'-'.$month.'-'.$last_day);

        $allowed_days = array();
        $list = DB::select()->from('line_suit_price')
            ->where("
                suitid='{$params['suit_id']}' 
                and day>={$start_time} 
                and day<={$end_time} 
                and supplier_channel_id={$params['channel_id']}
            ")
            ->execute()->as_array();
        foreach ($list as $key=>&$row)
        {
            $row['date'] = date('Y-m-d',$row['day']);
            $allowed_days[] = $row['date'];
            $row['number'] = $row['number']==-1?'不限':$row['number'];
        }

        return array(
            'list'         => $list,
            'starttime'    => date('Y-m-d',$start_time),
            'allowed_days' => $allowed_days
        );
    }

    /**
     * @param $params
     * @return bool[]
     * 清除报价
     */
    public static function delete_price($params)
    {
        $params = json_decode($params,true);
        DB::delete('line_suit_price')->where("suitid={$params['suit_id']} and supplier_channel_id IN({$params['channel_id']})")->execute();
        return array(
            'status' => true,
        );
    }

    /**
     * @param $params
     * @return array
     * 渠道产品列表
     */
    public static function channel_product_list($params)
    {
        $params = json_decode($params,true);
        $date = strtotime(date('Ymd'));
        $page = ($params['page']-1)*$params['page_size'];

        $sql = "SELECT a.id,a.refuse_msg,a.title,a.status,a.ishidden,a.supplier_channel_id FROM sline_line AS a ";
        $sql.= "LEFT JOIN sline_line_suit_price AS b ON(a.id=b.lineid) ";
        $sql.= "WHERE a.supplierlist={$params['supplier_id']} AND b.day>={$date} AND b.supplier_channel_id={$params['channel_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.title LIKE '%{$params['keyword']}%' OR a.id='{$params['keyword']}') ";
        }
        $sql.= "GROUP BY a.id ";
        $sql.= "ORDER BY a.modtime DESC,a.addtime DESC ";
        $total = DB::query(1, $sql)->execute()->count();
        $sql.= "LIMIT {$page},{$params['page_size']} ";
        $list = DB::query(1, $sql)->execute()->as_array();
        if(!$list){
            return array('status'=>false,'msg'=>'没有匹配的线路产品！');
        }
        foreach ($list as &$v){
            $v['status_name'] = Model_Supplier::status_name($v['status']);
            $max_day = DB::select(DB::expr('max(day) AS day') )->from('line_suit_price')->where("day>{$date} and lineid={$v['id']}")->execute()->get('day');
            $v['time_validity'] = date('Y-m-d',$max_day);
            $supplier_channel_id = explode(',',$v['supplier_channel_id']);
            $v['channel_status'] = in_array($params['channel_id'],$supplier_channel_id);
        }

        return array(
            'status'     => true,
            'list'       => $list,
            'total_page' => ceil($total/$params['page_size'])
        );
    }

}